import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import pickle
import matplotlib.pyplot as plt
import gradio as gr

# 加载保存的KNN模型
with open('best_knn_model.pkl', 'rb') as f:
    knn = pickle.load(f)

# 定义预测函数
def predict(image):
    # 将输入的图像转换为与训练数据相同的格式
    image = np.array(image).reshape(1, -1)
    # 使用预训练的KNN模型进行预测
    prediction = knn.predict(image)
    return prediction[0]

# 创建Gradio接口
demo = gr.Interface(
    predict,
    gr.Image(label="输入图像"),
    gr.Label(label="预测结果"),
    title="手写数字识别",
    description="输入一个手写数字图像，模型将预测出相应的数字。"
)

# 启动Gradio接口
if __name__ == "__main__":
    demo.launch()
# Print the best accuracy and corresponding k value
print(f"\nBest accuracy: {best_accuracy:.4f}")
print(f"Best k value: {best_k}")

# Plot the relationship between k values and accuracy
plt.figure(figsize=(10, 6))
plt.plot(range(1, 41), accuracies, marker='o')
plt.title('Relationship between K value and Accuracy')
plt.xlabel('K value')
plt.ylabel('Accuracy')
plt.grid(True)
plt.savefig('accuracy_plot.pdf')
print("Accuracy plot saved as 'accuracy_plot.pdf'")

print("\nProcess completed successfully!")